/**
 * SearchConfiguration.java
 */
package com.mht2017.common.config;

import java.util.Collection;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SearchConfiguration extends CompositeConfiguration {

	private static Logger logger = LoggerFactory.getLogger(SearchConfiguration.class);

	private int total;
	private int failed;
	private int success;

	@Override
	public String getString(String key, String defaultValue) {
		return log(key, super.getString(key, defaultValue));
	}

	@Override
	public Boolean getBoolean(String key, Boolean defaultValue) {
		return log(key, super.getBoolean(key, defaultValue));
	}

	@Override
	public Long getLong(String key, Long defaultValue) {
		return log(key, super.getLong(key, defaultValue));
	}

	@Override
	public Integer getInteger(String key, Integer defaultValue) {
		return log(key, super.getInteger(key, defaultValue));
	}

	private <T> T log(String key, T value) {
		total++;
		if (null != value) {
			success++;
			logger.info(String.format("加载配置(%s/%s): '%s' = '%s'", success, total, key, value));
		} else {
			failed++;
			logger.error(String.format("加载配置失败(%s/%s): '%s' = '%s'", failed, total, key, value));
		}
		return value;
	}

	@Override
	protected Object resolveContainerStore(String key) {
		// 先读取-D参数的配置
		String _dArgProperty = System.getProperty(key);
		if (StringUtils.isEmpty(_dArgProperty)) {
			return getProperty(key);
		} else {
			logger.info(String.format("加载配置(%s)，从命令行-D参数中获取到: '%s'", key, _dArgProperty));
			return _dArgProperty;
		}
	}

	@Override
	public Object getProperty(String key) {
		Object value = super.getProperty(key);
		if (null != value) {
			if (value instanceof Collection<?>) {
				value = StringUtils.join((Collection<?>) value, ',');
			} else if (value.getClass().isArray()) {
				value = StringUtils.join((Object[]) value, ',');
			}
		}
		return value;
	}

}
